<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { Input, message, Select, SelectOption, Tag } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { useVbenForm } from '#/adapter/form';
import { getLinkage } from '#/api/portal/linkage';
import { postModuleField, putModuleField } from '#/api/portal/moduleAttributes';
import Icon from '#/components/Icons';

const optionsArr = new Set(['checkbox', 'radio', 'select']);
const cascaders: any = ref([]);

const cascaderRef = ref();
const inputRef = ref();
const state: any = reactive({
  form: {
    type: '',
    options: [],
  },
  modal_type: '',
  inputVisible: false,
  inputValue: '',
  typeOptions: [
       { label: $t('admin.text'), value: 'text' },
    { label: $t('admin.textarea'), value: 'textarea' },
    { label: $t('admin.html'), value: 'html' },
    { label: $t('admin.radio'), value: 'radio' },
    { label: $t('admin.checkbox'), value: 'checkbox' },
    { label: $t('admin.select'), value: 'select' },
    { label: $t('admin.number'), value: 'number' },
    { label: $t('admin.image'), value: 'image' },
    { label: $t('admin.images'), value: 'images' },
    { label: $t('admin.file'), value: 'file' },
    { label: $t('admin.files'), value: 'files' },
    { label: $t('admin.switch'), value: 'switch' },
    { label: $t('admin.location'), value: 'location' },
    { label: $t('admin.cascader'), value: 'cascader' },
    { label: $t('admin.color'), value: 'color' },
    { label: $t('admin.time'), value: 'time' },
    { label: $t('admin.date'), value: 'date' },
    { label: $t('admin.datetime'), value: 'datetime' },
    { label: $t('admin.article_dataSource'), value: 'article_dataSource' }
    
  ],
});

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个属性改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个属性改变时，都会触发
        triggerFields: ['module_id'],
      },
      fieldName: 'module_id',
      label: 'module_id',
    },
    {
      component: 'Input',
      dependencies: {
        disabled(values) {
          return values.type === 'cascader';
        },
        // 随意一个属性改变时，都会触发
        triggerFields: ['name', 'id', 'title', 'type'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'title',
      label: $t('page.common.Title'),
      rules: 'required',
    },
    {
      component: 'Input',
      dependencies: {
        disabled(values) {
          return !!values.id || values.type === 'cascader';
        },
        // 随意一个属性改变时，都会触发
        triggerFields: ['name', 'id', 'title', 'type'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'name',
      label: $t('admin.attributeName'),
      rules: 'required',
    },
    {
      component: 'Select',
      defaultValue: '',
      dependencies: {
        disabled(values) {
          return !!values.id;
        },
        triggerFields: ['type', 'id'],
      },
      fieldName: 'type',
      label: $t('page.common.Category'),
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'options',
      dependencies: {
        show(values) {
          return optionsArr.has(values.type) || values.type === 'cascader';
        },
        trigger: (values, form) => {
          state.form.type = values.type;
          if (values.type === 'cascader' && values.options) {
            const filteredItem = cascaders.value.find(
              (item: any) => item.id === Number.parseInt(values.options, 10),
            );
            if (filteredItem) {
              form.setFieldValue('title', filteredItem.name);
              form.setFieldValue('name', filteredItem.code);
            }
          }
        },
        // 随意一个属性改变时，都会触发
        triggerFields: ['type', 'options'],
      },
      defaultValue: [],
      label: $t('admin.options'),
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      dependencies: {
        show(values) {
          return values.type !== 'cascader';
        },
        triggerFields: ['type'],
      },
      fieldName: 'default_value',
      label: $t('admin.defaultValue'),
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'tip',
      label: $t('admin.placeholder'),
    },
    {
      component: 'Switch',
      defaultValue: 1,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      fieldName: 'status',
      label: $t('page.common.Status'),
    },
  ],
  showDefaultActions: false,
});

const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      const {
        data: { list },
      } = await getLinkage();
      cascaders.value = list;

      if (values.form) {
        formApi.setValues(values.form);
        state.form = values.form;
      } else {
        state.form.options = [];
        formApi.setFieldValue('module_id', values.modeulID);
        state.modal_type = values.modalType;

        if (['parameter', 'spec'].includes(state.modal_type)) {
          const type = state.modal_type === 'spec' ? 'select' : 'text';
          formApi.updateSchema([
            {
              component: 'Input',
              componentProps: {
                placeholder: '请输入',
              },
              dependencies: {
                show: false,
                disabled: true,
                // 随意一个属性改变时，都会触发
                triggerFields: ['name', 'id', 'title'],
              },
              fieldName: 'title',
              label: '属性标题',
              rules: 'required',
            },
            {
              component: 'Input',
              dependencies: {
                disabled: false,
                trigger: (values) => {
                  if (state.modal_type !== 'module' && values.name) {
                    values.title = values.name;
                  }
                },
                // 随意一个属性改变时，都会触发
                triggerFields: ['name', 'id', 'title'],
              },
              componentProps: {
                placeholder: '请输入',
              },
              fieldName: 'name',
              label: '属性名称',
              rules: 'required',
            },
            {
              component: 'Select',
              defaultValue: '',
              dependencies: {
                show: false,
                triggerFields: ['type', 'id'],
              },
              fieldName: 'type',
              label: '数据类型',
            },
            {
              component: 'Select',
              fieldName: 'options',
              dependencies: {
                show: (values) => {
                  return values.type === 'select';
                },
                trigger: (values, form) => {
                  state.form.type = values.type;
                  if (values.type === 'cascader' && values.options) {
                    const filteredItem = cascaders.value.find(
                      (item: any) =>
                        item.id === Number.parseInt(values.options, 10),
                    );
                    if (filteredItem) {
                      form.setFieldValue('title', filteredItem.name);
                      form.setFieldValue('name', filteredItem.code);
                    }
                  }
                },
                // 随意一个属性改变时，都会触发
                triggerFields: ['type', 'options'],
              },
              defaultValue: [],
              label: $t('admin.options'),
            },
            {
              component: 'Input',
              defaultValue: '',
              componentProps: {
                placeholder: '请输入',
              },
              dependencies: {
                show: (values) => {
                  return values.type === 'text';
                },
                triggerFields: ['type'],
              },
              fieldName: 'default_value',
              label: '默认值',
            },
            {
              component: 'Input',
              defaultValue: '',
              dependencies: {
                show: false,
                // 随意一个属性改变时，都会触发
                triggerFields: ['name', 'id', 'title', 'tip'],
              },
              componentProps: {
                placeholder: '请输入',
              },
              fieldName: 'tip',
              label: '提示文字',
            },
          ]);

          formApi.setFieldValue('type', type);
        }
      }
    }
  },
});

const handleClose = (removedTag: string) => {
  const tags = state.form.options.filter((tag: any) => tag !== removedTag);
  state.form.options = tags;
};

const showInput = () => {
  state.inputVisible = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  const inputValue = state.inputValue;
  let tags = state.form.options || [];
  if (inputValue && !tags.includes(inputValue)) {
    tags = [...tags, inputValue];
  }
  Object.assign(state, {
    form: { options: tags },
    inputVisible: false,
    inputValue: '',
  });
  formApi.setValues(state.form);
};

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    state.form = {
      type: '',
      options: [],
    };
    state.inputVisible = false;
    state.inputValue = '';
    state.modal_type = '';
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  if (!optionsArr.has(values.type) && values.type !== 'cascader') {
    values.options = '';
  }
  if (values.id) {
    const { msg } = await putModuleField(values.id, values);
    showMsg(msg);
  } else {
    const { msg } = await postModuleField(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <Form>
      <template #type="slotProps">
        <Select v-bind="slotProps" placeholder="请选择" style="width: 100%">
          <SelectOption
            v-for="item in state.typeOptions"
            :key="item.value"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; font-size: 13px; color: #8492a6">
              {{ item.value }}
            </span>
          </SelectOption>
        </Select>
      </template>
      <template #options="slotProps">
        <template v-if="state.form.type === 'cascader'">
          <Select
            ref="cascaderRef"
            v-bind="slotProps"
            placeholder="请选择"
            style="width: 100%"
          >
            <SelectOption
              v-for="item in cascaders"
              :key="`${item.id}`"
              :value="`${item.id}`"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; font-size: 13px; color: #8492a6">
                {{ item.code }}
              </span>
            </SelectOption>
          </Select>
        </template>
        <template v-else>
          <div class="flex flex-wrap items-start">
            <template v-for="tag in state.form.options" :key="tag">
              <Tag class="mb-4" closable @close="handleClose(tag)">
                {{ tag }}
              </Tag>
            </template>
            <Input
              v-if="state.inputVisible"
              ref="inputRef"
              v-model:value="state.inputValue"
              :style="{ width: '78px' }"
              size="small"
              type="text"
              @blur="handleInputConfirm"
              @keyup.enter="handleInputConfirm"
            />

            <Tag
              v-else
              style="padding: 6px; background: #fff; border-style: dashed"
              @click="showInput"
            >
              <Icon icon="ri:add-line" />
            </Tag>
          </div>
        </template>
      </template>
    </Form>
  </Modal>
</template>

<style lang="scss" scoped></style>
